import { arrayMethods} from './array.js'
import { isObject,def } from '../util/index.js'
class Observer{
    constructor(value){
        def(value,'__ob__',this)
        if(Array.isArray(value)){
          value.__proto__ = arrayMethods
          this.observeArray(value)
        }else{
            this.walk(value)
        }
       
    }
    walk(data){
        let keys = Object.keys(data)
        keys.forEach(key => {
            this.defineReactive(data,key,data[key])
        })
    }
    defineReactive(data,key,value){
        observe(value)
        Object.defineProperty(data,key,{
            get(){
                console.log('用户获取值了')
                return value
            },
            set(newValue){
                console.log('用户设置值了')
                if(newValue === value) return
                value = newValue
                observe(value)
            }
        })
    }
    observeArray(arr){
        for(let i = 0; i<arr.length; i++){
            observe(arr[i])
        }
    }
}

export function observe(data){
    if(typeof data !== 'object' || data == null){
        return;
    }
    if(data.__ob__){
        return
    }
    return new Observer(data)
}